<template>
  <div class="notification-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">通知中心</span>
          <div class="header-actions">
            <el-button
              v-if="userStore.isTeacherOrAdmin"
              type="primary"
              @click="goToSendNotification"
            >
              <el-icon><Plus /></el-icon>
              发送通知
            </el-button>
            <el-button
              type="success"
              @click="markAllAsRead"
              :disabled="unreadCount === 0"
            >
              <el-icon><Check /></el-icon>
              全部已读
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选条件 -->
      <div class="filter-bar">
        <el-form :model="searchForm" inline>
          <el-form-item label="通知类型">
            <el-select
              v-model="searchForm.type"
              placeholder="全部类型"
              clearable
              style="width: 150px"
              @change="handleSearch"
            >
              <el-option
                v-for="type in NOTIFICATION_TYPES"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="阅读状态">
            <el-select
              v-model="searchForm.isRead"
              placeholder="全部状态"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option label="未读" :value="false" />
              <el-option label="已读" :value="true" />
            </el-select>
          </el-form-item>

          <el-form-item label="优先级">
            <el-select
              v-model="searchForm.priority"
              placeholder="全部优先级"
              clearable
              style="width: 120px"
              @change="handleSearch"
            >
              <el-option
                v-for="priority in NOTIFICATION_PRIORITIES"
                :key="priority.value"
                :label="priority.label"
                :value="priority.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计信息 -->
      <div class="stats-bar">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-statistic title="总通知数" :value="pagination.total" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="未读通知" :value="unreadCount" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="今日通知" :value="todayCount" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="本周通知" :value="weekCount" />
          </el-col>
        </el-row>
      </div>

      <!-- 通知列表 -->
      <div class="notification-content" v-loading="loading">
        <div v-if="notificationList.length === 0" class="empty-state">
          <el-empty description="暂无通知" />
        </div>

        <div v-else class="notification-items">
          <div
            v-for="notification in notificationList"
            :key="notification.id"
            class="notification-item"
            :class="{ 'unread': !notification.is_read }"
            @click="handleNotificationClick(notification)"
          >
            <div class="notification-icon">
              <el-icon :color="getPriorityColor(notification.priority)">
                <component :is="getNotificationTypeIcon(notification.notification_type)" />
              </el-icon>
            </div>

            <div class="notification-body">
              <div class="notification-header">
                <div class="notification-title">{{ notification.title }}</div>
                <div class="notification-meta">
                  <el-tag
                    :type="getPriorityTagType(notification.priority)"
                    size="small"
                  >
                    {{ getPriorityLabel(notification.priority) }}
                  </el-tag>
                  <el-tag
                    type="info"
                    size="small"
                    effect="plain"
                  >
                    {{ getNotificationTypeLabel(notification.notification_type) }}
                  </el-tag>
                  <span class="sender">来自: {{ notification.sender_name }}</span>
                  <span class="time">{{ formatTime(notification.created_at) }}</span>
                </div>
              </div>

              <div class="notification-content-text">{{ notification.content }}</div>
            </div>

            <div class="notification-actions">
              <el-tag
                v-if="!notification.is_read"
                type="danger"
                size="small"
                effect="plain"
              >
                未读
              </el-tag>

              <el-dropdown trigger="click" @command="(command: string) => handleAction(command, notification)">
                <el-button type="text" size="small">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-if="!notification.is_read"
                      command="markRead"
                    >
                      <el-icon><Check /></el-icon>
                      标记已读
                    </el-dropdown-item>
                    <el-dropdown-item command="delete" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="pagination.total > 0">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import {
  notificationApi,
  type Notification,
  NOTIFICATION_TYPES,
  NOTIFICATION_PRIORITIES,
  getNotificationTypeLabel,
  getPriorityLabel,
  getPriorityColor,
  getNotificationTypeIcon
} from '@/api/notifications'
import { formatTime } from '@/utils/format'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const notificationList = ref<Notification[]>([])
const unreadCount = ref(0)
const todayCount = ref(0)
const weekCount = ref(0)

// 搜索表单
const searchForm = reactive({
  type: '',
  isRead: null as boolean | null,
  priority: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 获取优先级标签类型
const getPriorityTagType = (priority: string): string => {
  const types: Record<string, string> = {
    low: 'info',
    normal: 'primary',
    high: 'warning',
    urgent: 'danger'
  }
  return types[priority] || 'primary'
}

// 获取通知列表
const fetchNotificationList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize,
      ...searchForm
    }

    // 清理空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })

    const response = await notificationApi.getNotificationList(params)
    const data = response.data || response
    notificationList.value = data.results || []
    pagination.total = data.count || 0
  } catch (error) {
    ElMessage.error('获取通知列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStatistics = async () => {
  try {
    // 获取未读数量
    const unreadResponse = await notificationApi.getUnreadCount()
    const unreadData = unreadResponse.data || unreadResponse
    unreadCount.value = unreadData.count

    // 获取今日通知数量（简化实现，实际应该从后端获取）
    const today = new Date()
    const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate())
    todayCount.value = notificationList.value.filter(n =>
      new Date(n.created_at) >= todayStart
    ).length

    // 获取本周通知数量（简化实现）
    const weekStart = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
    weekCount.value = notificationList.value.filter(n =>
      new Date(n.created_at) >= weekStart
    ).length
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.page = 1
  fetchNotificationList()
}

// 重置搜索
const handleReset = () => {
  searchForm.type = ''
  searchForm.isRead = null
  searchForm.priority = ''
  pagination.page = 1
  fetchNotificationList()
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  fetchNotificationList()
}

// 处理页码变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchNotificationList()
}

// 处理通知点击
const handleNotificationClick = async (notification: Notification) => {
  // 如果未读，标记为已读
  if (!notification.is_read) {
    try {
      await notificationApi.markAsRead(notification.id)
      notification.is_read = true
      notification.read_at = new Date().toISOString()
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }
}

// 处理操作
const handleAction = async (command: string, notification: Notification) => {
  switch (command) {
    case 'markRead':
      try {
        await notificationApi.markAsRead(notification.id)
        notification.is_read = true
        notification.read_at = new Date().toISOString()
        unreadCount.value = Math.max(0, unreadCount.value - 1)
        ElMessage.success('已标记为已读')
      } catch (error) {
        ElMessage.error('标记失败')
      }
      break

    case 'delete':
      try {
        await ElMessageBox.confirm('确定要删除这条通知吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await notificationApi.deleteNotification(notification.id)
        ElMessage.success('删除成功')
        fetchNotificationList()
      } catch (error: any) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
      break
  }
}

// 标记所有通知为已读
const markAllAsRead = async () => {
  try {
    await ElMessageBox.confirm('确定要标记所有通知为已读吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await notificationApi.markAllAsRead()
    ElMessage.success('已标记所有通知为已读')

    // 更新本地状态
    notificationList.value.forEach(notification => {
      notification.is_read = true
    })
    unreadCount.value = 0
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 跳转到发送通知页面
const goToSendNotification = () => {
  router.push('/notifications/send')
}

// 生命周期
onMounted(async () => {
  await fetchNotificationList()
  await fetchStatistics()
})
</script>

<style lang="scss" scoped>
.notification-list {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 18px;
      font-weight: 600;
      color: var(--text-color-primary);
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .filter-bar {
    margin-bottom: 20px;
    padding: 16px;
    background: var(--fill-color-extra-light);
    border-radius: 6px;
  }

  .stats-bar {
    margin-bottom: 20px;
    padding: 16px;
    background: var(--fill-color-light);
    border-radius: 6px;
  }

  .notification-content {
    .empty-state {
      padding: 40px 0;
    }

    .notification-items {
      .notification-item {
        display: flex;
        align-items: flex-start;
        padding: 16px;
        border: 1px solid var(--border-color-extra-light);
        border-radius: 8px;
        margin-bottom: 12px;
        cursor: pointer;
        transition: all 0.3s ease;

        &:hover {
          border-color: var(--color-primary-light-7);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        &.unread {
          background: var(--color-primary-light-9);
          border-left: 4px solid var(--color-primary);
        }

        &:last-child {
          margin-bottom: 0;
        }

        .notification-icon {
          margin-right: 16px;
          margin-top: 4px;

          .el-icon {
            font-size: 20px;
          }
        }

        .notification-body {
          flex: 1;
          min-width: 0;

          .notification-header {
            margin-bottom: 8px;

            .notification-title {
              font-size: 16px;
              font-weight: 600;
              color: var(--text-color-primary);
              margin-bottom: 6px;
              line-height: 1.4;
            }

            .notification-meta {
              display: flex;
              align-items: center;
              gap: 8px;
              flex-wrap: wrap;

              .sender {
                font-size: 12px;
                color: var(--text-color-secondary);
              }

              .time {
                font-size: 12px;
                color: var(--text-color-placeholder);
              }
            }
          }

          .notification-content-text {
            color: var(--text-color-regular);
            line-height: 1.6;
            display: -webkit-box;
            -webkit-line-clamp: 3;
            -webkit-box-orient: vertical;
            overflow: hidden;
          }
        }

        .notification-actions {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-left: 16px;
        }
      }
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 24px;
    }
  }
}

@media (max-width: 768px) {
  .notification-list {
    .card-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 12px;

      .header-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .filter-bar {
      .el-form {
        .el-form-item {
          margin-bottom: 12px;
        }
      }
    }

    .stats-bar {
      .el-col {
        margin-bottom: 16px;
      }
    }

    .notification-content {
      .notification-items {
        .notification-item {
          .notification-body {
            .notification-header {
              .notification-meta {
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
              }
            }
          }

          .notification-actions {
            flex-direction: column;
            margin-left: 8px;
          }
        }
      }
    }
  }
}
</style>